package com.dxj1992.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dxj1992.entity.AdminRolePermissions;
import com.dxj1992.entity.AdminRoles;
import com.dxj1992.mapper.AdminRolePermissionsMapper;
import com.dxj1992.mapper.AdminRolesMapper;
import com.dxj1992.service.IAdminRolePermissionsService;
import com.dxj1992.service.IAdminRolesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author jobob
 * @since 2022-04-01
 */
@Service
public class AdminRolesServiceImpl extends ServiceImpl<AdminRolesMapper, AdminRoles> implements IAdminRolesService {

    @Autowired
    private AdminRolesMapper adminRolesMapper;

    @Autowired
    private AdminRolePermissionsMapper adminRolePermissionsMapper;

    @Autowired
    private IAdminRolePermissionsService adminRolePermissionsService;

    @Override
    public boolean editSave(AdminRoles adminRoles) {
        adminRolesMapper.updateById(adminRoles);
        List<AdminRolePermissions> adminRolePermissions = adminRolePermissionsMapper.selectList(Wrappers.<AdminRolePermissions>lambdaQuery().eq(AdminRolePermissions::getAdminRoleId, adminRoles.getId()));
        for (AdminRolePermissions adminRolePermission : adminRolePermissions) {
            adminRolePermissionsMapper.delete(Wrappers.<AdminRolePermissions>lambdaQuery().eq(AdminRolePermissions::getAdminRoleId, adminRolePermission.getAdminRoleId()));
        }

        List<AdminRolePermissions> list = new ArrayList<>();
        for (long menuId : adminRoles.getMenuIds()) {
            AdminRolePermissions rolePermissions = new AdminRolePermissions();
            rolePermissions.setAdminRoleId(adminRoles.getId());
            rolePermissions.setAdminPermissionId(new Long(menuId).intValue());
            list.add(rolePermissions);
        }

        adminRolePermissionsService.saveBatch(list, 50);
        return true;
    }

    @Override
    public List<AdminRoles> selectRoleById(Integer id) {

        List<AdminRoles> adminRoles = adminRolesMapper.selectRoleById(id);
        List<AdminRoles> roles = adminRolesMapper.selectList(null);

        for (AdminRoles role : roles) {
            for (AdminRoles adminRole : adminRoles) {
                if (adminRole.getId() == role.getId()) {
                    role.setFlag(true);
                }
            }
        }
        return roles;
    }
}
